<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

// no direct access
defined('_JEXEC') or die('Restricted access');


/**
 * @package		Joomla
 * @subpackage	jl_profile
 */
class JAJobBoardControllerJAPaymentconfig extends JAJobBoardController{
	/*
	* Constructor
     */
    function __construct( $location = array() )
    {
    	
        parent::__construct( $location );  
        checkPermission_Administrator('paymentconfig');    
        // Register Extra tasks
        $this->registerTask( 'add',     'edit' );
        $this->registerTask( 'apply',   'save' );
    }
    
	function display()
	{
		switch ($this->getTask())
		{			
			case 'add':
			case 'edit':
				{
					JRequest::setVar( 'layout', 'form'  );	
					break;					
				}
			default:
				{
					JRequest::setVar( 'layout', 'default'  );				
					break;
				}
		}
		
		parent::display();
	}
	
	function install(){
		global $option;
		$db = JFactory::getDBO();
		//print_r($_FILES);exit;
		if(isset($_FILES) && $_FILES['pay_file']['name']){
			$filename = $_FILES['pay_file']['name'];
			$type = substr($filename, -3, 3);
			if($type!='zip'){
				JError::raiseWarning(1, JText::_("File format is incorrect").".".JText::_("The file must be ZIP type"));
				return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=add");
			}
			jimport('joomla.filesystem.file');
			$temp_desk = JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS.$filename;
			$desk = JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS.substr($filename,0,strlen($filename)-strlen(JFile::getExt($filename))-1).'.php';
			
			/*if( JFile::exists($desk) ) {
				JError::raiseWarning(1, JText::_("This file actually exists. Please check again."));
				echo "<br/>".JText::_("Delete exist file and continue install");
				return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=add");
			}*/
			
			if(JFile::upload($_FILES['pay_file']['tmp_name'], $temp_desk)){
				jimport('joomla.filesystem.file');
				jimport('joomla.filesystem.folder');
				jimport('joomla.filesystem.archive');
				jimport('joomla.filesystem.path');
				$temp_result = JArchive::extract($temp_desk,JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS);
				unlink($temp_desk = JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS.$filename);
				
				$vars = new stdClass();
				$vars->name = substr($filename, 0, strlen($filename)-strlen(JFile::getExt($filename))-1);
				$vars->published  = 0;
				$vars->alias  = $vars->name;
				$correct_payment = true;
				if (!JFile::exists($desk))
				{
					$arr_file = JFolder::files(JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS);
					for ($i=0;$i<count($arr_file);$i++)
					{
						if (substr($arr_file[$i],0,strlen($arr_file[$i])-strlen(JFile::getExt($arr_file[$i]))-1)==$vars->name)
						{
							unlink(JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS.$arr_file[$i]);
						}
					}
					$correct_payment = false;
					
				}
				else 
				{
					require_once($desk);
					if (!$this->check_correct_payment_structure($vars->name))
					{
						$correct_payment = false;
						unlink($desk);
					}
				}
				if (!$correct_payment)
				{
					JError::raiseWarning(1, JText::_("This file is incorrect structure. Please try again."));
					return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=add");
				}
				$sql = $db->setQuery("select id from #__ja_paymentconfig where name='{$vars->name}'");
				$result = $db->loadResult($sql);
				if($result){
					JError::raiseWarning(1, JText::_("Payment name actually exists. Please check again."));
					return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=add");
				}											
				if ($vars->name=='wirebank')
				{
					$params = new JParameter();
					$params->set('wirebank_information','<table border="0" cellspacing="0" cellpadding="0">\n<tbody>\n<tr>\n<td colspan="2" align="left"><img src="components/com_jajobboard/images/payments/wirebank/payment_step_one.png" border="0" alt="Wire Transfer Payment step 1" width="40" height="19" align="top" />Please make the wire transfer as follows Amount need to be transferred: {Currency}<span style="color: #ff0000; font-size: 18px;"> {Amount}</span><span style="color: #ff0000;"> (All banking fee, local bank and international wire transfer <strong><span style="text-decoration: underline;">MUST BE PAID BY SENDER</span></strong>.)</span> Payment ID: <span style="color: #0000ff; font-size: 18px;">{Transaction ID} </span><span style="color: #0000ff;">   Must be included in your payment detail </span></td>\n</tr>\n<tr>\n<td><br /></td>\n</tr>\n<tr>\n<td colspan="2" align="left">Please make a wire transfer to the following bank account:</td>\n</tr>\n<tr>\n<td><br /></td>\n</tr>\n<tr>\n<td>Account holder:</td>\n<td align="left"><strong> Name of Beneficial </strong></td>\n</tr>\n<tr>\n<td>Bank:</td>\n<td align="left"><strong>Bank Nam<br /></strong></td>\n</tr>\n<tr>\n<td>Bank Address</td>\n<td align="left">6 Battery Road, xxx 049909</td>\n</tr>\n<tr>\n<td>SWIFT:</td>\n<td align="left"><strong>xxxxxx</strong></td>\n</tr>\n<tr>\n<td>BANK ACCOUNT NUMBER</td>\n<td align="left"><strong>001122334455</strong></td>\n</tr>\n<tr>\n<td>Account currency:</td>\n<td align="left"><strong>USD</strong></td>\n</tr>\n<tr>\n<td>Reference:</td>\n<td align="left"><strong><span style="color: #0000cc;">{Username} - Payment {Transaction ID}</span> <img src="components/com_jajobboard/images/payments/wirebank/not.png" border="0" /> Your username and Payment ID MUST BE PROVIDED! </strong></td>\n</tr>\n<tr>\n<td><br /></td>\n</tr>\n<tr>\n<td colspan="2" align="left"><img src="components/com_jajobboard/images/payments/wirebank/payment_step_two.png" border="0" alt="Wire Transfer Payment step 2" align="top" /> Email us the Payment Receipt.\n<div id="ja_align"><span>Depending on the provided receipt, we can active your account within 24 business hours.</span> <img src="components/com_jajobboard/images/payments/wirebank/wire_sample1.jpg" border="0" alt="Wire Transfer Payment Receipt Sample 1" align="top" /> <img src="components/com_jajobboard/images/payments/wirebank/wire_sample2.jpg" border="0" alt="Wire Transfer Payment Receipt Sample 2" align="top" />\n<div class="small">\n<li> <strong>Currency of payments:</strong> We recommend you to send the transfer  in the {Currency}. For transfers in other  currencies, you may be subject to foreign exchange  charges. </li>\n<br />\n<li> <strong>We cannot debit the amount from your bank account:</strong> You need to instruct the bank transfer by yourself! </li>\n<br />\n<li> <strong>International Transfer!</strong> This  payment will be an international bank wire transfer and may be subject to  processing and/or intermediary bank charges. {Site name} cannot be held liable  for such charges. </li>\n</div>\n</div>\n</td>\n</tr>\n</tbody>\n</table>');
					$vars->datas = $params->toString();
				}
				if(!$db->insertObject('#__ja_paymentconfig', $vars)){
					JError::raiseWarning(1, JText::_("Insert DB error."));
					return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=add");
				}
				
				return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=edit&pay={$vars->name}", JText::_("Successfully installed. Please continue to configure the parameters"));
			}
			else{
				JError::raiseWarning(1, JText::_("Upload file error occurs. Please try again."));
				return $this->setRedirect("index.php?option=$option&view=japaymentconfig&task=add");
			}
		}
	}
	
	function save()
	{
		$data = JRequest::get('post');
				
		$id = JRequest::getInt('id', 0);
		if($id)$obj->id = $id;
		$obj->alias = $data['alias'];		
		$obj->published = $data['published'];
		
		$datas = JRequest::getVar($data['name'], array(), 'post', 'array');						
		
		$params = new JParameter(array());
		foreach ($datas as $k=>$value){
			$params->set($k, $value);
		}
		$obj->datas = $params->toString();
		$obj->custom_payment_completed_mail = $data['custom_payment_completed_mail'];
		$obj->custom_payment_pending_mail = $data['custom_payment_pending_mail'];
		
		$db = JFactory::getDBO();
		if(!$db->updateObject('#__ja_paymentconfig', $obj, 'id')){
			JError::raiseError(1, JText::_('An error occurred during update.'));
			$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig&task=edit&pay='.$data['name']);
		}
		if($this->getTask()=='apply'){
			$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig&task=edit&pay='.$data['name'], JText::_("Successfully updated payment method"));
		}
		else	$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig', JText::_("Successfully updated payment method"));
				
	}
	function cancel()
	{
		$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig');
	}
	function remove()
	{
		$cids=JRequest::getVar('cid',null);
		if(!$cids)
			$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig', JText::_("Please select payment method"));
		else 
		{	
			if(!is_array($cids))$cids=array();
			$cid = implode(",",$cids);
			$model = $this->getModel('japaymentconfig');
			jimport('joomla.filesystem.file');
			
			foreach ($cids as $id){
				$list = $model->getTypes(" WHERE id in ($cid)");
				if($list){
					foreach ($list as $row){
						$desk = JPATH_COMPONENT_SITE.DS.'asset'.DS.'payments'.DS.$row->name.'.php';
						if(JFile::exists($desk))	JFile::delete($desk);
					}
				}				
			}
			
			if($model->remove($cid))
				$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig', JText::_("Successfully deleted payment method"));
			else 
				$this->setRedirect('index.php?option=com_jajobboard&view=japaymentconfig', JText::_("Error found!Fail to delete payment method"));
		}
	}
	function publish()
	{
		global $mainframe;
		$model = $this->getModel('japaymentconfig');
		if(!$model->published(1))
		{
			$msg = JText::_( 'Error found!Fail to publish payment' );
		} else {
			$msg = JText::_( 'Successfully published payment' );
		}
		
		$mainframe->redirect( 'index.php?option=com_jajobboard&view=japaymentconfig', $msg);		
	}
	function unpublish()
	{
		global $mainframe;
		$model = $this->getModel('japaymentconfig');
		if(!$model->published(0))
		{
			$msg = JText::_( 'Error founnd!Fail to unpublished payment' );
		} else {
			$msg = JText::_( 'Successfully published payment' );
		}
		
		$mainframe->redirect( 'index.php?option=com_jajobboard&view=japaymentconfig', $msg);		
	}
	function check_correct_payment_structure($class_name)
	{
		if (!class_exists($class_name))
			return false;
		$temp_object = new $class_name();
		if (!method_exists($temp_object,'__construct'))
			return false;
		if (!method_exists($temp_object,'config_form'))
			return false;
		if (!method_exists($temp_object,'more_info'))
			return false;
		if (!method_exists($temp_object,'check_payment'))
			return false;			
		if (!method_exists($temp_object,'payment_return'))
			return false;
		if (!method_exists($temp_object,'payment_cancel'))
			return false;
		if (!method_exists($temp_object,'assign_params'))
			return false;
		return true;
	}
	
}
?>